package org.example.springbook.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
//import lombok.extern.slf4j.Slf4j;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.example.springbook.constant.Constants;
import org.example.springbook.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
//   @Autowired
    private ObjectMapper objectMapper=new ObjectMapper();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("登录拦截，，");
        HttpSession session=request.getSession(false);
        if(session==null||session.getAttribute(Constants.SESSION_USER_KET)==null ||!StringUtils.hasLength((String) session.getAttribute(Constants.SESSION_USER_KET))){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.getOutputStream().write("{\"ok\":false}".getBytes());
            response.setContentType("application/json;charset=utf-8");

            return false;
        }
        return true;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//       log.info("执行postHandle");
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        log.info("执行afterCompletion");
//    }
}
